package com.peak.distribution.web.validator.method;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.google.common.collect.Maps;
import com.peak.distribution.web.validator.ValidateRuleMethod;
import com.peak.spring.boot.core.mapper.JsonMapper;
import com.peak.spring.boot.tools.Converts;
import com.peak.spring.boot.tools.Emptys;
import com.peak.spring.boot.tools.HttpClients;
import com.peak.spring.boot.tools.PropertiesLoader;

public class BankCard implements ValidateRuleMethod {
	
	private String bank;
	
	private String errorMessage;
	
	@Override
	public boolean execute(Object value) {
		if (Emptys.isEmpty(value)) {// 空的数据不校验，使用Require类校验
			return true;
		}
		Map<String, String> param = Maps.newHashMap();
		param.put("_input_charset", "utf-8");
		param.put("cardNo", Converts.toString(value));
		param.put("cardBinCheck", Boolean.TRUE.toString());
		String jsonResult = HttpClients.get("https://ccdcapi.alipay.com/validateAndCacheCardInfo.json", param);
		Map<String, Object> map = JsonMapper.nonDefaultMapper().fromJson(jsonResult, HashMap.class, String.class, Object.class);
		if ("ok".equals(Converts.toString(map.get("stat"))) && Converts.toBoolean(map.get("validated"))) { // 验证卡号正确性
			if ("DC".equalsIgnoreCase(Converts.toString(map.get("cardType")))) {// 借记卡
				PropertiesLoader loader = new PropertiesLoader("classpath:format.properties");
				if (StringUtils.equals(loader.getMap("agent.bank").get(this.bank), Converts.toString(map.get("bank")))) {
					return true;
				} else {
					this.errorMessage = "{0}" + value + "不是" + this.bank + "的银行卡";
				}
			} else {
				this.errorMessage = "{0}" + value + "必须是借记卡/储蓄卡，目前不支持信用卡";
			}
		} else {
			this.errorMessage = "{0}" + value + "的卡号不正确";
		}
		return false;
	}

	@Override
	public String getErrorMessageTemplate() {
		return this.errorMessage;
	}

	@Override
	public void setParams(Map<String, Object> param) {
		// 应该没啥吧
		this.bank = Converts.toString(param.get("bank"));
	}

}
